#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
sys.path.insert(0, '.')

import os
import pandas as pd

device_file = r'../Device.csv'
out_device_list_path = r'../SameUnitDevice.txt'


def main():
    device_cvs = pd.read_csv(device_file, sep=',')
    device_ids = device_cvs['设备ID']
    xiao_qus = device_cvs['所属小区']
    xiao_qu_positions = device_cvs['小区位置']

    xiao_qu_position_device_id_infos = {}
    for device_id, xiao_qu, xiao_qu_position in zip(device_ids, xiao_qus, xiao_qu_positions):
        if xiao_qu == '爱丽丝':
            _xiao_qu_position = xiao_qu
        else:
            _xiao_qu_position = '{},{}'.format(xiao_qu, ' '.join(xiao_qu_position.split()[:-2]))
        device_id_infos = xiao_qu_position_device_id_infos.get(_xiao_qu_position, None)
        if device_id_infos is None:
            xiao_qu_position_device_id_infos[_xiao_qu_position] = [[device_id], [xiao_qu_position]]
        else:
            device_id_infos[0].append(device_id)
            device_id_infos[1].append(xiao_qu_position)

    with open(out_device_list_path, 'w', encoding='utf-8') as file:
        xiao_qu_positions = list(xiao_qu_position_device_id_infos.keys())
        xiao_qu_positions.sort()
        for _xiao_qu_position in xiao_qu_positions:
            device_id_infos = xiao_qu_position_device_id_infos[_xiao_qu_position]
            xiao_qu = _xiao_qu_position.split(',')[0]
            device_ids, positions = device_id_infos
            device_id_str = ','.join(device_ids)
            position_str = ','.join(positions)
            out_info = '{};{};{}\n'.format(xiao_qu, device_id_str, position_str)
            file.write(out_info)
    os.system('chmod a+wr {}'.format(out_device_list_path))
    print('Finish!')

if __name__ == '__main__':
    main()
